/*--
 * TextExporter.cs: Exports a registry branch to a REGEDIT4 format text file.
 *--
 * For more information, please visit the Registrar Project site:
 *   http://code.google.com/p/registrar/
 *--
 * (c) 2006 Christopher E. Granade.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; exactly version 2
 * of the License applies to this software.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
 
using System;
using System.IO;
using Microsoft.Win32;

namespace Registrar {
	
	
	public class TextSerializer : IRegistrySerializer {
		
		/// <summary>
    	/// Converts an array of bytes represented as byte[] to a string of
    	/// hexadecimal digits that represents the same value.
    	/// A comma is inserted after each byte (two digits).
    	/// </summary>
    	/// <param name="bytes">The array to be converted.</param>
    	public static string BytesToHex(byte[] bytes) {
    	
	    	string hex = "";

            foreach(byte b in bytes) {
        		hex += b.ToString("x") + ",";
            }

            return hex.Substring(0, hex.Length - 1);

      	}
		
		private const string header = "REGEDIT4\n";
		private StreamWriter sw;
		
		public void Import(string target) {
		
		}
		
		public void Export(RegistryKey rk, string target) {
			
			FileStream fs = File.Open(target, FileMode.Create);
			sw = new StreamWriter(fs);
			
			// Write the header.
			sw.WriteLine(header);
			
			// Starting with the given registry key, recusively descend into the
			// branch and encode each part as text.
			ExportKey(rk);
			
			sw.Close();
			
		}
		
		private string EscapeChar(string s, char c) {
			return s.Replace(c.ToString(), "\\" + c.ToString());
		}
		
		private string Escape(string s) {
			
			string e = s;
			e = EscapeChar(e, '\\');
			e = EscapeChar(e, '"');
			
			return ("\"" + e + "\"");
			
		}
		
		private void ExportKey(RegistryKey rk) {
			
			sw.WriteLine("[{0}]", rk.Name);
			
			// TODO: Add handling for default values!
			
			// Print the values.
			foreach (string vname in rk.GetValueNames()) {
				
				object o = rk.GetValue(vname);
				
				// Get the value string.
				string s = "";
				
				if (o is string)
					s = Escape(((string)o));
				else if (o is byte[])
					s = "hex:" + BytesToHex((byte[])o);
				else if (o is int)
					s = "dword:" + String.Format("{0:x8}", (int)o);
				
				sw.WriteLine("\"{0}\"={1}", vname, s);
				
			}
			
			// Print a blank line.
			sw.WriteLine();
			
			// Now, print each subkey.
			foreach (string kname in rk.GetSubKeyNames()) {
				ExportKey(rk.OpenSubKey(kname, false));
			}
			
		}
		
	}
	
}
